package myCine.alloCine.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import myCine.alloCine.model.exchange.search.Search;
import myCine.alloCine.model.exchange.search.subClass.Movie;
import utils.Constantes;
import utils.StringUtils;

import com.google.gson.Gson;

//String json = readUrl("http://api.allocine.fr/rest/v3/movie?partner=YW5kcm9pZC12M3M&code=61282&profile=large&mediafmt=mp4-lc&format=json&filter=movie&striptags=synopsis,synopsisshort");
//Gson gson = new Gson();
//Search search = gson.fromJson(json, Search.class);
//System.out.println(search.getMovie().getStatistics().getUserRating() + "/5");

public class Services {
	
	public final static Gson gson = new Gson();

	
	/*=========================
	 * 	  	SERVICES
	 *=========================*/
	
	/**
	 * Search movies by name
	 * @return return null if no result, else one Movies or a feed of items
	 */
	public static Search searchMovies(final String name) throws Exception{
		
		Search search = null;
		
		if(StringUtils.isNotEmpty(name)){
			String json = readUrl(Constantes.URL_ALLOCINE + "search?"
					+ Constantes.PARAM_COMMON
					+ "&" + Constantes.PARAM_FILTER_MOVIE
					+ "&q=" + name);
			search = gson.fromJson(json, Search.class);
		}
		
		return search;
	}
	
	/**
	 * Get details of the movie
	 * @param movieCode unique identifier 
	 * @throws Exception 
	 */
	public static Movie movieDetails(final Integer movieCode) throws Exception {
		
		Search search = null;
		
		if(movieCode != null && movieCode > 0){
			String request = Constantes.URL_ALLOCINE + "movie?"
					+ Constantes.PARAM_COMMON
					+ "&code=" + movieCode
					+ "&profile=large"
					+ "&striptags=synopsis,synopsisshort";
			String json = readUrl(request);
			search = gson.fromJson(json, Search.class);
		}
		
		return search.getMovie();
	}
	
	/*=========================
	 * 	  	  UTILS
	 *=========================*/
	
	/**
	 * Call the URL and get content webpage
	 */
    private static String readUrl(String urlString) throws Exception {
    	
        BufferedReader reader = null;

        try{
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader (url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[]chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read); 

            return buffer.toString();
        } finally {
            if (reader != null)
                reader.close();
        }

    }
}
